import type { JSX } from 'vue/jsx-runtime'
// import type { NodeListItem } from '@/apis/model/node'
// import {
//   Form,
//   FormItem,
//   Message,
//   Select,
// } from '@arco-design/web-vue'
import {
  Button,
  Divider,
  Form,
  FormItem,
  Input,
  Message,
  // Select,

} from '@arco-design/web-vue'
import { useClipboard } from '@vueuse/core'
import IconArrowRight from '~icons/icons/arrow-right'

import IconCopy from '~icons/icons/copy'

import {
  deleteCdnNodeApi,
  getVersionInstallCommandApi,
  getVersionLatestApi,
  postCdnNodeControlApi,
  updateCdnNodeApi,
  updateVersionSwitchApi,
} from '@/apis/modules/cdn'

import { NODE_OPERATIONS } from '@/constants/cdn-node'

export default function useCommand(reload: () => void) {
  const handleCommand = (
    command: string,
    ids: string[],
    // row?: NodeListItem,
    row?: any,
  ) => {
    const {
      getVersionDescription,
      switchVersion,
      batchChangeVersion,
      singleVersionChange,
    } = versionControl(reload)
    const controlNode = (type: NODE_OPERATIONS, content: string) => {
      const fn = () =>
        postCdnNodeControlApi({ control_type: type, ids }).then(() => {
          Message.success('操作成功')
          reload()
        })
      if ([NODE_OPERATIONS.STOP, NODE_OPERATIONS.RELOAD].includes(type)) {
        ModalHelper.error(
          {
            maskClosable: false,
            content,
            width: 480,
          },
          fn,
        )
      } else {
        ModalHelper.confirm(
          {
            width: 480,
            maskClosable: false,
            content,
          },
          fn,
        )
      }
    }
    const map: Record<string, () => void> = {
      start: () => {
        // 启用
        const content = `启用所选 ${ids.length} 个节点，开始向终端用户提供服务，确认继续？`
        controlNode(NODE_OPERATIONS.START, content)
      },
      startOne: () => {
        // 启用
        const content = `启用节点 “${row?.name}” ，确认继续？`
        controlNode(NODE_OPERATIONS.START, content)
      },
      stop: () => {
        const content = `停用所选 ${ids.length} 个节点，停止向终端用户提供服务，确认继续？`
        // 停用
        controlNode(NODE_OPERATIONS.STOP, content)
      },
      stopOne: () => {
        // 停用
        const content = `停用节点 “${row?.name}” ，确认继续？`
        controlNode(NODE_OPERATIONS.STOP, content)
      },
      reload: () => {
        // 重启
        const content = `重启所选 ${ids.length} 个节点，确认继续？`
        controlNode(NODE_OPERATIONS.RESTART, content)
      },
      reloadOne: () => {
        // 重启
        const content = `重启节点 “${row?.name}” ，确认继续？`
        controlNode(NODE_OPERATIONS.RESTART, content)
      },
      join: () => {
        const fn = () =>
          updateCdnNodeApi({ id: ids[0] as string, enable_resolve: true }).then(
            () => {
              Message.success('操作成功')
              reload()
            },
          )
        // 加入解析
        ModalHelper.confirm(
          {
            maskClosable: false,
            content: `将节点 IP “${row?.ips ? row?.ips[0] : ''}” 加入解析链路，确认继续？`,
          },
          fn,
        )
      },
      remove: () => {
        const fn = () =>
          updateCdnNodeApi({
            id: ids[0] as string,
            enable_resolve: false,
          }).then(() => {
            Message.success('操作成功')
            reload()
          })

        // 移除解析
        ModalHelper.error(
          {
            maskClosable: false,
            content: `将节点 IP “${row?.ips ? row?.ips[0] : ''}” 从解析链路中移除，确认继续？`,
          },
          fn,
        )
      },
      version: async () => {
        // await getVersionOpts(true)
        await getVersionDescription()
        // let descriptions = ''
        // if (ids.length === 1) {
        //   descriptions = await getVersionDescription(row!.version!)
        // }
        const title = '升级版本'
        // const fn
        //   = ids.length > 1
        //     ? batchChangeVersion(ids.length)
        //     : singleVersionChange(descriptions, row?.version)
        const fn
        = batchChangeVersion(ids.length)

        ModalHelper.confirm(
          {
            title,
            maskClosable: false,
            width: 480,
            content: fn,
          },
          () => switchVersion(ids),
        )
      },
      config: () => {
        // 批量同步配置
        const fn = () =>
          postCdnNodeControlApi({
            control_type: NODE_OPERATIONS.SYNC,
            ids,
          }).then(() => {
            Message.success('操作成功')
            reload()
          })
        ModalHelper.error(
          {
            maskClosable: false,
            width: 480,
            content: () => (
              <div class="flex flex-col gap-y-6 text-3">
                <span>
                  {/* 该操作会重置所选节点的配置，清空并重新生成相关联站点配置，确认继续？ */}
                  重新生成并下发所选
                  {' '}
                  {ids.length}
                  {' '}
                  个节点的相关配置，确认继续？
                </span>
                <span class="text-#86909C">
                  *注意：若涉及到大量节点和站点时可能耗时较长
                </span>
              </div>
            ),
          },
          fn,
        )
      },
      cache: () => {
        // 清除缓存
        const fn = () =>
          postCdnNodeControlApi({
            control_type: NODE_OPERATIONS.PURGE,
            ids,
          }).then(() => {
            Message.success('操作成功')
            reload()
          })
        ModalHelper.error(
          {
            width: 480,
            maskClosable: false,
            content: `清除所选 ${ids.length} 个节点的所有缓存，缓存将在数分钟后失效，确认继续？`,
          },
          fn,
        )
      },
      delete: () => {
        const nameVerification = reactive({ name: '' })
        const disabled = computed(() => nameVerification.name !== row?.name)
        const loading = ref(false)
        const modalReturn = ref()

        const fn = () => {
          loading.value = true
          deleteCdnNodeApi({ id: ids[0] as string })
            .then(() => {
              Message.success('操作成功')
              modalReturn.value.close()
              reload()
            })
            .finally(() => {
              loading.value = false
            })
        }

        // 删除节点
        modalReturn.value = ModalHelper.error(
          {
            maskClosable: false,
            // content: text,
            okText: '确定',
            width: 480,
            title: '删除节点',
            footer: () => {
              return row?.installed
                ? (
                    <div class="flex justify-end">
                      <Button onClick={() => modalReturn.value.close()} class="mr-4">
                        取消
                      </Button>
                      <Button
                        status="danger"
                        disabled={disabled.value}
                        class={disabled.value ? 'bg-[#FBACA3]!' : ''}
                        style={disabled.value ? '' : ''}
                        onClick={() => fn()}
                        loading={loading.value}
                      >
                        我已知晓后果并确认删除
                      </Button>
                    </div>
                  )
                : null
            },
            content: () =>
              row?.installed
                ? (
                    <div class="w-full flex flex-col gap-y-6 text-#1D2129">
                      <span class={`text-[#1D2129] `}>
                        删除并卸载节点 “
                        {row?.name}
                        ” ，此操作无法撤销。
                      </span>
                      <div class="w-full">
                        <Form layout="vertical" model={nameVerification}>
                          <FormItem
                            asteriskPosition="end"
                            field="name"
                            validateTrigger="blur"
                            hide-asterisk
                            // rules={[
                            //   {
                            //     required: true,
                            //     validator(value, cb) {
                            //       if (!value) {
                            //         return cb('请输入提示内容')
                            //       }
                            //       if (value !== row?.name) {
                            //         return cb('请输入提示内容')
                            //       }
                            //       return cb()
                            //     }
                            //   }
                            // ]}
                          >
                            {{
                              label: () => (
                                <span class="text-#1D2129">
                                  请输入「
                                  <span class="text-red-500">{row?.name}</span>
                                  」确认
                                </span>
                              ),
                              default: () => (
                                <Input
                                  class="mb-2px w-full"
                                  modelValue={nameVerification.name}
                                  maxLength={32}
                                  onInput={(v) => {
                                    nameVerification.name = v
                                  }}
                                  placeholder=""
                                >
                                </Input>
                              ),
                            }}
                          </FormItem>
                        </Form>
                      </div>
                    </div>
                  )
                : (
                    `确认删除节点 “${row?.name}” ？`
                  ),
          },
          fn,
        )
      },
      install_script: async () => {
        const { renderInstallScript, getScript, formState } = getInstallScript()
        await getScript(ids[0] as string)
        if (!formState.url)
          return false
        ModalHelper.confirm({
          title: '安装命令',
          maskClosable: false,
          footer: false,
          width: 480,
          content: renderInstallScript,
        })
      },
    }
    map[command]()
  }
  return { handleCommand }
}

/**
 *
 * 安装脚本弹窗
 */
function getInstallScript() {
  const formState = reactive({ url: '' })
  const { copy } = useClipboard({ legacy: true })
  const handleCopy = (content: string) => {
    copy(content)
    Message.success('复制成功')
  }
  async function getScript(id: string) {
    return getVersionInstallCommandApi({
      id,
    })
      .then((res) => {
        formState.url = res.command ?? ''
      })
      .catch(() => {
        return true
      })
  }
  const renderInstallScript = () => (
    <div class="mb-[12px] w-full flex flex-col gap-y-6 text-[#1D2129]">
      {/* <div class="flex justify-between">
        <span>请复制命令在目标节点目标服务器中进行安装</span>
        <span
          class="flex gap-x-6px items-center text-primary cursor-pointer"
          onClick={() => handleCopy(formState.url ?? '')}>
          <IconCopy />
          复制
        </span>
      </div> */}
      <div class="flex justify-between gap-4 rounded-2 bg-#1D2129 p-4 text-white">
        <div>{formState.url}</div>
        <div>
          <div
            class="w-20px flex cursor-pointer items-center gap-x-6px text-white"
            onClick={() => handleCopy(formState.url ?? '')}
          >
            <IconCopy />
          </div>
        </div>
      </div>
    </div>
  )

  return {
    formState,
    getScript,
    renderInstallScript,
  }
}

/**
 * 版本切换弹窗
 * @param reload 重新获取列表数据
 */
function versionControl(reload: () => void) {
  const versionsOpt = ref<LabelValue[]>([])

  const targetVersion = reactive({ version: '', id: '' })
  const targetDesc = ref('')
  // 版本说明
  function versionDescription(des?: string) {
    return (
      <FormItem class="version-item">
        {/* <div
          class={[
            'text-12px text-wrap whitespace-pre-line max-h-[200px] overflow-auto w-full',
            { 'text-2!': des },
          ]}
        >
          {des && des !== '-' ? des : '此版本暂无说明'}
        </div> */}

        {{
          label: () => (
            <span class="text-12px text-#86909C">版本说明</span>
          ),
          default: () => (
            <div
              class={[
                'text-12px text-wrap whitespace-pre-line max-h-[200px] overflow-auto w-full',
              ]}
            >
              {des && des !== '-' ? des : '此版本暂无说明'}
            </div>
          ),
        }}
      </FormItem>
      // <div class="flex flex-col gap-y-2">
      //   <span class="text-4">版本说明</span>
      //   <div
      //     class={['text-4 text-wrap whitespace-pre-line', { 'text-2!': des }]}>
      //     {des && des !== '-' ? des : '此版本暂无说明'}
      //   </div>
      // </div>
    )
  }

  // function compareVersions(a: number[], b: number[], index: number): number {
  //   if (index > Math.max(a.length, b.length)) return 1
  //   if (a[index] > b[index]) return 1
  //   if (a[index] < b[index]) return -1
  //   return compareVersions(a, b, index + 1)
  // }
  // 获取版本列表
  // async function getVersionOpts(init: boolean = false) {
  //   try {
  //     const res = await getVersionListApi({
  //       limit: 1000,
  //       order: 'desc',
  //       sort: 'version',
  //     })
  //     const list = res.list ?? []
  //     versionsOpt.value
  //       = list.map(item => ({
  //         label: item.version ?? '',
  //         value: item.id ?? '',
  //       })) ?? []
  //     if (init) {
  //       targetDesc.value = await getVersionDescription()
  //     }
  //   } catch (_err) {
  //     console.error(_err)
  //     versionsOpt.value = []
  //   }
  // }
  // 获取版本描述
  async function getVersionDescription(): Promise<string> {
    try {
      const res = await getVersionLatestApi()
      targetVersion.id = res.id ?? ''
      targetVersion.version = res.version ?? ''
      targetDesc.value = res.imprint ?? ''
      return res.imprint ?? ''
    } catch (error) {
      console.error(error)
      return ''
    }
  }
  // const versionChange = async (id: string) => {
  //   targetVersion.id = id
  //   const version
  //     = versionsOpt.value.find(item => item.value === id)?.label ?? ''
  //   targetDesc.value = await getVersionDescription(version)
  // }
  // 批量切换版本
  const batchChangeVersion = (num?: number) => {
    const node = (
      <div class="w-full">
        <div class="mb-2 text-[#8F959E]">
          {num > 1
            ? (
                <>
                  将所选
                  {' '}
                  {num}
                  {' '}
                  个节点升级为
                  {' '}
                  <span class="text-[#1D2129] font-bold">{targetVersion.version}</span>
                  {' '}
                  版本
                </>
              )
            : (
                <>
                  版本：
                  {' '}
                  <span class="text-[#1D2129] font-bold">{targetVersion.version}</span>
                </>
              )}

        </div>
        <Divider type="dashed" />
        <Form layout="vertical" model={targetVersion}>
          {/* <FormItem
            asteriskPosition="end"
            label="切换版本"
            required
            field="id"
            hide-asterisk
          >
            <Select
            modelValue={targetVersion.id}
            options={versionsOpt.value}
            placeholder="请选择版本"
            onChange={v => versionChange(v as string)}
          >
          </Select>
          </FormItem> */}
          {versionDescription(targetDesc.value)}
        </Form>

      </div>
    )
    return num
      ? (
          <div class="w-full">
            <div class="min-h-60 w-full flex flex-col gap-y-4 border rounded p-4">
              {node}
            </div>
          </div>
        )
      : (
          node
        )
  }

  function versionWrap(children: () => JSX.Element) {
    return (
      <div class="min-h-60 w-346px flex flex-col gap-y-4 border rounded p-4 border-color-3 bg-fill-1">
        {children()}
      </div>
    )
  }
  // 版本切换
  const singleVersionChange = (desc: string, currentVersion: string = '') => {
    const currentInfo = () => (
      <Form model={{}} layout="vertical">
        <FormItem label="当前版本" class="version-item">
          <span class="text-2">{currentVersion || '-'}</span>
        </FormItem>
        {versionDescription(desc)}
      </Form>
    )
    return () => (
      <div class="h-full flex gap-x-4">
        {versionWrap(currentInfo)}
        <div class="flex items-center">
          <IconArrowRight />
        </div>
        {versionWrap(batchChangeVersion)}
      </div>
    )
  }
  const switchVersion = (ids: string[]) =>
    updateVersionSwitchApi({
      ids,
      target_id: targetVersion.id,
    }).then(() => {
      Message.success('操作成功')
      reload()
    })
  return {
    singleVersionChange,
    batchChangeVersion,
    switchVersion,
    getVersionDescription,
  }
}
